<?php

namespace app\controller\Api\V1\Client\Lander;

use app\helper\GetProductInfo;
use app\model\GameAuthorization;
use app\model\GameEngine;
use app\model\GameRecommendConfig;
use app\model\GameSell;
use app\model\LanderService;
use app\model\LanderServiceGroup;
use app\model\LanderVersion;
use app\model\ToolServer;
use App\model\DistrictService;
use app\request\Lander;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use support\Request;
use support\Response;

class ListController
{

    protected GetProductInfo $getProductInfoRe;


    public function __construct()
    {
        $this->getProductInfoRe = GetProductInfo::getInstance();
    }




    /**
     * 栩腾区服列表接口（4-2-2 标准）
     *
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function listXuTeng(Request $request): Response
    {
        try {
            // 1️⃣ 获取请求参数
            $appId = (int) $request->input('appId');
            $time = (string) $request->input('time');
            $pageIndex = max(1, (int) $request->input('pageIndex'));
            $pageSize = max(1, (int) $request->input('pageSize'));
            $sign = (string) $request->input('sign');

            // 2️⃣ 基本参数校验
            if (!$appId || !$time || !$sign) {
                return jsonRe(['code' => 400, 'msg' => '参数错误', 'data' => []]);
            }

            // 3️⃣ 校验签名 sign = md5(appid + time + appkey)
            $appKey = 'd3d716b0246d71dc860d97275c7c653b'; // 例如从配置中读取 appkey
            $checkSign = md5($appId . $time . $appKey);

            if ($checkSign !== strtolower($sign)) {
                return jsonRe(['code' => 401, 'msg' => '签名错误', 'data' => []]);
            }

            $game = GameAuthorization::query()
                ->where('t_game', $appId)
                ->value('ulid');


            // ️查询区服数据
            $query = DistrictService::query()->where('game', $game);
//            $query = DistrictService::query()->where('game', $game)->where('is_test', 1);
            $totalCount = (clone $query)->count();
            $list = $query->latest('created_at')
                ->skip(($pageIndex - 1) * $pageSize)
                ->take($pageSize)
                ->get()
                ->map(function ($row) {

                    // 状态判断逻辑
                    if ($row->is_merge_zone == 1) {
                        $status = 5; // 合服
                    } elseif ($row->is_maintenance == 1) {
                        $status = 2; // 维护
                    } elseif ($row->state == 0) {
                        $status = 3; // 停服
                    } else {
                        $status = 1; // 正常
                    }

                    return [
                        'serverId' => $row->ulid ?? '', //区服id
                        'serverName' => $row->OfficialAreaConfig->title ?? '', //区服名称
                        'status' => $status, //服务器状态 1正常 2维护 3停服 4待维护 5合服
                        'openTime' => strtotime($row->OfficialAreaConfig->open_at ?? 'now'), //开服时间 时间戳 秒
                        'mergeCount' => 0,
                        'openDays' => 0,
                        'mergeDays' => 0,
                        'mergeTime' => 0,
                        'masterId' => 0,
                    ];
                })->toArray();

            // 5️⃣ 统计开服数量（可根据 status=1 判断为开服）
            $openSize = (clone $query)->where('state', 1)->count();

            // 6️⃣ 返回结果
            return json([
                'code' => 0,
                'msg' => '成功',
                'data' => [
                    'openSize' => $openSize, //开服区服数量
                    'size' => $totalCount,   //总区服数量
                    'serverVos' => $list
                ]
            ]);
        } catch (\Throwable $e) {
            // 捕获所有异常，返回 code=500
            return json([
                'code' => 500,
                'msg' => '服务器内部错误: ' . $e->getMessage(),
                'data' => []
            ]);
        }
    }



    /**
     * 获取区服列表
     *
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function List(Request $request): Response
    {

        $validate = new Lander();

        if (!$validate->scene('list')->check($request->all())) {
            throw new Exception($validate->getError(), 500);
        }

        $recommendList = [];
        if ($request->input('release_type') == 0) {  // 测试服
            if (!empty($request->input('mch_id'))) {  // 商户测试服
                if (empty($this->getProductInfoRe->GetMerchantPlatform())) {
                    throw new Exception('未找到项目', 500);
                }
                $productInfo = $this->getProductInfoRe->GetMerchantPlatform();
                $user = $request->input('mch_id');
                $groupTitle = '商户工具服分组';
            } elseif (!empty($request->input('open_id'))) {  // 开发者测试服
                if (empty($this->getProductInfoRe->GetDeveloperPlatform())) {
                    throw new Exception('未找到项目', 500);
                }
                $productInfo = $this->getProductInfoRe->GetDeveloperPlatform();
                $user = $request->input('open_id');
                $groupTitle = '开发者工具服分组';
            } else {
                throw new Exception('参数非法', 500);
            }

            $list = ToolServer::query()->where('product', $productInfo['ulid'])->where('organization', $user)
                ->where(function (\Illuminate\Contracts\Database\Eloquent\Builder $query) use ($request) {
                    if ($request->input('game_id') != 0) {
                        $query->where('ulid', $request->input('game_id'));
                    }
                })->latest()->get()->map(function ($row) {
//                    $m2State = false;
//                    if ($row['m2_state'] === 1 && $row['state'] === 1) {
//                        $m2State = true;
//                    }

                    // 内网测试服m2状态默认开启
                    $m2State = true;

                    return [
                        'id' => $row['id'],
                        'ulid' => $row['ulid'],
                        'title' => $row['title'],
                        'color' => null,
                        'is_recommend' => 0,
                        'state' => 1,  // 1畅通 2拥挤 3爆满
                        'server' => [
                            'instance_ip' => $row['ip'],
                            'instance_port' => $row['port'],
                            'm2_state' => $m2State,
                        ],
                        'district_service' => [
                            'ulid' => $row['ulid'],
                            'list_title' => $row['title'],
                            'is_test' => 1,
                            'color' => null,
                            'open_at' => date('Y-m-d H:i:s', strtotime($row['created_at'])),
                            'is_test_area' => 0,
                            'state' => $row['state'],  // 区服状态
                        ],
                    ];
                })->toArray();

            $recommendItem = $list[0] ?? [];

            $resultList[] = [
                'ulid' => $user,
                'title' => $groupTitle,
                'color' => null,
                'children' => $list,
            ];
        } else {  // 正式服
            if (empty($request->input('mch_id'))) {
                throw new Exception('请选择商户', 500);
            }

            // 获取游戏推荐区服配置
            $recommendConfig = GameRecommendConfig::query()->where('merchant', $request->input('mch_id'))
                ->where('game', $request->input('game_id'))->first();
            if (!$recommendConfig) {
                $recommendConfig = [];
            } else {
                $recommendConfig = $recommendConfig->toArray();
            }

            if ($recommendConfig && $recommendConfig['type'] === 2) {  // 强制推荐
                $lastLanderService = LanderService::query()->where('merchant', $request->input('mch_id'))
                    ->where('game', $request->input('game_id'))->where('is_recommend', 1)
                    ->oldest('sort')->latest('show_at')->first();
            } else {
                $lastLanderService = LanderService::query()->where('merchant', $request->input('mch_id'))
                    ->where('game', $request->input('game_id'))->where('show_at', '<=', date('Y-m-d H:i:s'))
                    ->oldest('sort')->latest('show_at')->first();
            }
            $lastLanderServiceId = $lastLanderService?->id;

            $list = LanderServiceGroup::query()->where("merchant", $request->input('mch_id'))
                ->where('game', $request->input('game_id'))
                ->where('show_at', '<=', date('Y-m-d H:i:s'))
                ->get();

            $resultList = [];
            $defaultRecommendArea = [];
            foreach ($list as $item) {
                $children = LanderService::query()->with(['Server', 'DistrictService'])
                    ->where("parent_ulid", $item['ulid'])
                    ->whereHas('Server', function (Builder $query) {
                        $query->where('state', 1)
                            ->where('expire_at', ">", date('Y-m-d H:i:s'));
                    })
                    ->whereHas('DistrictService', function (Builder $query) {
                        $query->where('show_at', "<", date('Y-m-d H:i:s'));
                    })
                    ->where('show_at', "<", date('Y-m-d H:i:s'))
                    ->orderByDesc("is_recommend")->oldest('sort')
                    ->latest()->get()->map(function ($itemA) {
                        if ($itemA->DistrictService['is_test'] && strtotime($itemA->DistrictService->OfficialAreaConfig['open_at']) > time()) {
                            $areaName = $itemA->DistrictService->TestAreaConfig['title'];
                            $openAt = $itemA->DistrictService->TestAreaConfig['open_at'];
                            $isTestArea = true;
                        } else {
                            $areaName = $itemA->DistrictService->OfficialAreaConfig['title'];
                            $openAt = $itemA->DistrictService->OfficialAreaConfig['open_at'];
                            $isTestArea = false;
                        }

                        if (strtotime($openAt) > time()) {
                            $areaState = 0;  // 未到开区时间
                        } else {
                            if ($itemA->Server['state'] !== 1) {
                                $areaState = 4; // 已关服
                            } else {
                                $areaState = $itemA['state'];  // 1畅通 2拥挤 3爆满
                            }
                        }

                        $m2State = false;
                        if ($itemA->Server['m2_state'] === 1 && $itemA->DistrictService['state'] === 1 && in_array($areaState, [1, 2, 3])) {
                            $m2State = true;
                        }

                        $server = [
                            'instance_ip' => $itemA->Server['instance_ip'],
                            'instance_port' => !empty($itemA->Server['gate_login_port']) ? $itemA->Server['gate_login_port'] : $itemA->Server['instance_port'],
                            'm2_state' => $m2State,
                        ];

                        return [
                            'id' => $itemA['id'],
                            'ulid' => $itemA['ulid'],
                            'title' => $areaName,
                            'color' => $itemA['color'],
                            'is_recommend' => $itemA['is_recommend'],
                            'state' => $areaState,
                            'server' => $server,  // 服务器信息
                            'district_service' => [
                                'ulid' => $itemA->DistrictService['ulid'],
                                'list_title' => $areaName,
                                'is_test' => $itemA->DistrictService['is_test'],
                                'color' => $itemA['color'],
                                'open_at' => $openAt,
                                'is_test_area' => $isTestArea,
                                'state' => $itemA->DistrictService['state'],  // 区服状态
                            ],  // 区服信息
                        ];
                    })->toArray();

                $resultList[] = [
                    'ulid' => $item['ulid'],
                    'title' => $item['title'],
                    'color' => $item['color'],
                    'children' => $children,
                ];

                foreach ($children as $itemB) {
                    if (empty($defaultRecommendArea)) {
                        $defaultRecommendArea = $itemB;
                    }

                    if ($recommendConfig && $recommendConfig['state']) {
                        if ($itemB['is_recommend']) {
                            if ($recommendConfig['only_recommend_official'] === 1) {
                                if (!$itemB['district_service']['is_test_area']) {
                                    $recommendList[] = $itemB;
                                }
                            } else {
                                $recommendList[] = $itemB;
                            }
                        }
                    } else {
                        if ($itemB['id'] === $lastLanderServiceId) {
                            $defaultRecommendArea = $itemB;
                        }
                    }
                }
            }

            if (count($recommendList) > 0) {
                $recommendItem = Arr::random($recommendList);
            } else {
                $recommendItem = $defaultRecommendArea;
            }
        }


        //  获取最新游戏引擎版本号
        $gameEngineInfo = GameEngine::query()->where('state', 1)->latest('ulid')->first();
        if ($gameEngineInfo) {
            $gameEngine = $gameEngineInfo['title'];
        } else {
            $gameEngine = '';
        }

        // 获取最新登陆器版本号
        $landerVersionInfo = LanderVersion::query()->where('package_type', $request->input('release_type'))
            ->where('package_platform', $request->input('promotion_platform'))->where('state', 1)
            ->latest('ulid')->first();
        if ($landerVersionInfo) {
            $landerVersion = $landerVersionInfo['title'];
        } else {
            $landerVersion = '';
        }

        return jsonRe([
            'engine_version' => $gameEngine,
            'lander_version' => $landerVersion,
            'default' => $recommendItem ?? [],
            'list' => $resultList,
        ]);

    }

}
